package com.hys.authserver.auth;

import com.hys.authserver.api.vo.AuthReq;
import com.hys.authserver.api.vo.AuthRes;
import com.hys.authserver.utils.JwtUtils;
import com.hys.authserver.utils.RedisUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class AuthenticationService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisUtils redisUtils;

    public AuthRes authenticate(AuthReq authReq) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                new SmsAuthenticationToken(
                        authReq.getUsername(),
                        authReq.getPassword()
                )
            );
            String uuid= UUID.randomUUID().toString();
            AuthUserDetails userDetails = (AuthUserDetails) authentication.getDetails();

            log.info("Authentication successful for user: {}", userDetails.getUsername());
            log.info("Generated UUID: {}", uuid);

            String jwt=JwtUtils.createToken(uuid,userDetails.getUsername(),userDetails.getPhone(), userDetails.getUid(), userDetails.getAuthoritiesStr());

            redisUtils.deleteJwtUuidKey(userDetails.getUsername());
            //验证是否有效,如果有效redis 会存储uuid
            redisUtils.setJwtUuidKey(userDetails.getUsername(),uuid);
            //登录成功后删除验证码
            redisUtils.deleteSmsCodeKey(authReq.getUsername());

            return AuthRes.builder()
                    .token(jwt)
                    .username(userDetails.getUsername())
                    .phone(userDetails.getPhone())
                    .uid(userDetails.getUid())
                    .expire(RedisUtils.JWT_TOKEN_EXPIRE_TIME)
                    .role(userDetails.getAuthoritiesStr())
                    .build();
        } catch (DisabledException e) {
            log.warn("Authentication failed because user is disabled: {}", authReq.getUsername());
            throw new DisabledException("User disabled", e);
        } catch (LockedException e) {
            log.warn("Authentication failed because user is locked: {}", authReq.getUsername());
            throw new LockedException("User locked", e);
        } catch (BadCredentialsException e) {
            log.warn("Authentication failed because of bad credentials: {}", authReq.getUsername());
            throw new BadCredentialsException("Bad credentials", e);
        } catch (Exception e) {
            log.error("Authentication failed: {}", e.getMessage());
            throw new RuntimeException("Error authenticating user", e);
        }
    }

    public void logout(String username){
        redisUtils.deleteJwtUuidKey(username);
    }
}
